package com.gorkr.servicepassengeruser.service.impl;

import com.gorkr.servicepassengeruser.dao.ServicePassengerUserInfoCustomDao;
import com.gorkr.servicepassengeruser.entity.ServicePassengerUserInfo;
import com.gorkr.servicepassengeruser.service.PassengerUserService;
import com.mashibing.internalcommon.constant.RedisKeyPrefixConstant;
import com.mashibing.internalcommon.dto.ResponseResult;
import com.mashibing.internalcommon.util.JwtUtil;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author gorkr
 * @date 2022/05/28 15:47
 **/
@Service
public class PassengerUserServiceImpl implements PassengerUserService {

    @Resource
    private ServicePassengerUserInfoCustomDao servicePassengerUserInfoCustomDao;

    @Resource
    private RedisTemplate<String,String > redisTemplate;

    @Override
    public ResponseResult login(String passengerPhone) {
        // 如果数据库没有此用户，插库。可以用分布锁，也可以用 唯一索引。
        // 为什么此时用手机号？
        // 查出用户id

        ServicePassengerUserInfo passengerUserInfo = new ServicePassengerUserInfo();
        passengerUserInfo.setCreateTime(new Date());
        passengerUserInfo.setPassengerGender((byte)1);
        passengerUserInfo.setPassengerName("");
        passengerUserInfo.setRegisterDate(new Date());
        passengerUserInfo.setUserState((byte)1);

        servicePassengerUserInfoCustomDao.insertSelective(passengerUserInfo);

        Long passengerId = passengerUserInfo.getId();

        String token = JwtUtil.createToken(passengerId + "", new Date());
        // 存入redis，设置过期时间
        BoundValueOperations<String, String> stringStringBoundValueOperations = redisTemplate.boundValueOps(RedisKeyPrefixConstant.PASSENGER_LOGIN_TOKEN_APP_KEY_PRE + passengerId);
        stringStringBoundValueOperations.set(token,30, TimeUnit.DAYS);



        return ResponseResult.success(token);
    }
}
    